package top.go2do.email.business.email.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.go2do.common.dao.UserRepository;
import top.go2do.common.enumeration.CommonStatus;
import top.go2do.common.enumeration.RegisterSource;
import top.go2do.common.module.UserPO;
import top.go2do.common.utils.CryptUtils;
import top.go2do.common.utils.IdUtils;
import top.go2do.email.business.email.module.RegisterDTO;
import top.go2do.email.exception.EmailException;
import top.go2do.websiteNavigation.exception.EmailErrorCode;

@Service
public class EmailUserServiceImpl implements EmailUserService{

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private IdUtils idUtils;

    @Override
    public void judgeEmailUserExist(String appId, String email) {
        UserPO userPO = userRepository.findByAppIdAndEmail(appId, email);
        if (userPO != null) {
            throw new EmailException(EmailErrorCode.EMAIL_EXIST);
        }
    }

    @Override
    public void createEmailUser(RegisterDTO registerDTO) {
        UserPO userPO = new UserPO();
        Long userId = idUtils.getSnowflakeId();
        userPO.setUserId(userId);
        userPO.setAppId(registerDTO.getAppId());
        userPO.setEmail(registerDTO.getEmail());
        userPO.setUsername("");
        String passwordSaveHash = CryptUtils.encode(registerDTO.getPassword());
        userPO.setPasswordHash(passwordSaveHash);
        userPO.setStatus(CommonStatus.NORMAL.getValue());
        Long registerSource = Long.valueOf(RegisterSource.EMAIL_REGISTER.getValue());
        userPO.setCreatedBy(registerSource);
        userPO.setUpdatedBy(registerSource);
        userRepository.save(userPO);
    }
}
